<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace app\common\services\user;

use app\common\dao\user\UserAuthDao;
use app\common\services\BaseServices;
use hdphp\exceptions\AuthException;
use hdphp\services\CacheService;
use hdphp\utils\JwtAuth;

/**
 * Class：用户授权服务
 * 创建人：Jack
 * 创建时间：2024/1/17 10:13
 * @package app\services\user
 * @mixin UserAuthDao
 */
class UserAuthServices extends BaseServices
{
    /**
     * 构造函数
     * @param UserAuthDao $dao
     */
    public function __construct(UserAuthDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 注释：获取授权信息
     * 创建人：Jack
     * 创建时间：2024/1/17 10:16
     * @param $token
     * @return array
     */
    public function parseToken($token): array
    {
        $md5Token = is_null($token) ? '' : md5($token);

        if ($token === 'undefined') {
            throw new AuthException('请登录', 410000);
        }
        if (!$token || !$tokenData = CacheService::getTokenBucket($md5Token))
            throw new AuthException('请登录', 410000);

        if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
            throw new AuthException('请登录', 410000);
        }

        /** @var JwtAuth $jwtAuth */
        $jwtAuth = app()->make(JwtAuth::class);
        // 设置解析token
        [$id, $type, $auth] = $jwtAuth->parseToken($token);
        try {
            $jwtAuth->verifyToken();
        } catch (\Throwable $e) {
            if (!request()->isCli()) CacheService::clearToken($md5Token);
            throw new AuthException('登录已过期,请重新登录', 410001);
        }

        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        $user = $userService->getUserCacheInfo($id);
        if (!$user) throw new AuthException('用户不存在，请重新登陆', 410001);
        if (!$user['status'])
            throw new AuthException('您已被禁止登录，请联系管理员', 410002);

        if (!$user || $user->uid != $tokenData['uid']) {
            if (!request()->isCli()) CacheService::clearToken($md5Token);
            throw new AuthException('登录状态有误,请重新登录', 410002);
        }

        // 有密码在检测
        if ($user['pwd'] != md5('123456') && $auth !== md5($user['pwd'])) {
            throw new AuthException('登录已过期,请重新登录', 410001);
        }

        $tokenData['type'] = $type;
        return compact('user', 'tokenData');
    }


}